import { Table, Select, Button, message } from 'antd'
import { useState, useRef } from 'react'
import { queryOmnibusConfig } from '@/api/base-config.js'
import { useEffect } from 'react'
import {
  dataTypeOptions,
  SHOW_TYPE_VALUE,
  SHOW_TYPE_ENUM,
  SHOW_TYPE_ARRAY,
  DATA_TYPE_WSTRING,
  DATA_TYPE_INT8,
} from '../../../components/config-edit-table/constant.js'
import TypeInput from '../../../components/config-edit-table/type-input.jsx'
import ArrayInput from '../../../components/config-edit-table/array-input.jsx'
import QuotenSelect from '../quoten-select/index.jsx'
import { getBaseInfoAttr, saveBaseInfoAttr } from '@/api/project-flow.js'

const dataTypeMap = {}
dataTypeOptions.forEach((item) => {
  dataTypeMap[item.value] = item
})

const NodeAttrTable = (props) => {
  const {projectId, nodeData, nameChange } = props

  const [attrList, setAttrList] = useState([])
  const [protocolTypeMap, setProtocolTypeMap] = useState({})

  const protocolTypeList = (attr) => {
    const protocolType = attr.protocol_type
    if (!protocolType) {
      return
    }

    if (protocolTypeMap[protocolType]) {
      return
    } else {
      queryOmnibusConfig({
        projectId: projectId,
        configType: protocolType,
        pageNum: 1,
        paegSize: 1000,
      }).then((res) => {
        let list = res.data.pageInfo ? res.data.pageInfo.list : []
        list = list.map(item => {
          return {
            value: item.id,
            label: item.configName
          }
        })
        
        protocolTypeMap[protocolType] = list
        setProtocolTypeMap({ ...protocolTypeMap })
      })
    }
  }

  useEffect(() => {
    if (nodeData && nodeData.nodeId) {
      getBaseInfoAttr({ id: nodeData.nodeId }).then((res) => {
        const attrResultList = res.data
        attrResultList.sort((a, b) => a.sort_num - b.sort_num)
        setAttrList(attrResultList || [])
        if (attrResultList) {
          attrResultList.forEach((attr) => {
            protocolTypeList(attr)
          })
        }
      })
    } else {
      setAttrList([])
      setProtocolTypeMap({})
    }
  }, [nodeData])

  const updateValue = (data) => {
    let tempData = [...data]
    setAttrList(tempData)
  }

  const setFieldData = (index, field, value) => {
    attrList[index][field] = value
    updateValue(attrList)
  }

  const [currentIndex, setCurrentIndex] = useState(null)
  const [visible, setVisible] = useState(false)

  const onSuccess = (value) => {
    setFieldData(currentIndex, 'attr_content', value)
  }
  const onCancel = () => {
    setVisible(false)
    setCurrentIndex(null)
  }

  const onDoubleClick = (index, record) => {
    if (record.data_type === DATA_TYPE_WSTRING && nodeData.typeCode == '2') {
      setCurrentIndex(index)
      setVisible(true)
    }
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render(text, record, index) {
        return index + 1
      },
    },
    {
      title: '别名',
      dataIndex: 'attr_name',
      key: 'attr_name',
      width: '25%',
    },
    {
      title: '属性名称',
      dataIndex: 'attr_code',
      key: 'attr_code',
      width: '26%',
    },
    {
      title: '属性值',
      dataIndex: 'attr_content',
      key: 'attr_content',
      width: '33%',
      render: (text, record, index) => {
        if (record.protocol_type) {
          return (
            <Select
              options={protocolTypeMap[record.protocol_type] || []}
              value={text}
              onChange={(value) => {
                setFieldData(index, 'attr_content', value)
              }}
              placeholder="请选择"
              style={{width: '100%'}}
            />
          )
        }

        let result = null
        let options = []
        switch (record.attr_type) {
          case SHOW_TYPE_VALUE:
            result = (
              <div onDoubleClick={() => onDoubleClick(index, record)}>
                <TypeInput
                  type={record.data_type}
                  min={dataTypeMap[record.data_type].min}
                  max={dataTypeMap[record.data_type].max}
                  value={text}
                  onChange={(value) => {
                    setFieldData(index, 'attr_content', value)
                  }}
                />
              </div>
            )
            break
          case SHOW_TYPE_ENUM:
            options = record.attr_range
              ? record.attr_range.split(',').map((item) => {
                  return { value: item, label: item }
                })
              : []
            result = (
              <Select
                options={options}
                value={text}
                onChange={(value) => {
                  setFieldData(index, 'attr_content', value)
                }}
                placeholder="请选择"
                style={{ width: '100%' }}
              />
            )
            break
          case SHOW_TYPE_ARRAY:
            result = (
              <ArrayInput
                type={record.data_type}
                min={dataTypeMap[record.data_type].min}
                max={dataTypeMap[record.data_type].max}
                value={text}
                onChange={(value) => {
                  setFieldData(index, 'attr_content', value)
                }}
              />
            )
            break
        }

        return result
      },
    },
  ]

  const otherTableProps = {
    rowKey: 'id',
    tableLayout: 'fixed',
    pagination: false,
    // bordered: true,
    size: 'small',
  }

  const [scroll, setScroll] = useState()
  const containerRef = useRef(null)

  useEffect(() => {
    if (containerRef.current) {
      let y = containerRef.current.clientHeight - 90
      y = attrList.length * 48 < y ? false : y
      setScroll(y ? { y } : null)
    }
  }, [containerRef, attrList])

  const [saving, setSaving] = useState(false)
  const onSave = () => {
    setSaving(true)
    saveBaseInfoAttr(attrList)
      .then((res) => {
        message.success('保存成功')
        nameChange(nodeData, attrList[0].attr_content)
        setSaving(false)
      })
      .catch(() => {
        setSaving(false)
      })
  }

  return (
    <div className="top-bottom-layout">
      <div className="flex-1">
        <div ref={containerRef} style={{ height: '100%' }}>
          <Table
            dataSource={attrList}
            columns={columns}
            {...otherTableProps}
            scroll={scroll}
          />
          <QuotenSelect
            nodeData={nodeData}
            visible={visible}
            onSuccess={onSuccess}
            onCancel={onCancel}
          />
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        {attrList.length > 0 && (
          <Button className='icon-btn' loading={saving} size="small" type="text" onClick={onSave}>
            保存
          </Button>
        )}
      </div>
    </div>
  )
}

NodeAttrTable.displayName = 'NodeAttrTable'

export default NodeAttrTable
